package com.baizhi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baizhi.dto.Result;
import com.baizhi.dto.ScrollResult;
import com.baizhi.dto.UserDTO;
import com.baizhi.entity.Blog;
import com.baizhi.entity.Follow;
import com.baizhi.entity.Shop;
import com.baizhi.entity.User;
import com.baizhi.mapper.BlogMapper;
import com.baizhi.service.IBlogService;
import com.baizhi.service.IFollowService;
import com.baizhi.service.IShopService;
import com.baizhi.service.IUserService;
import com.baizhi.utils.RedisConstants;
import com.baizhi.utils.SystemConstants;
import com.baizhi.utils.UserHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gange
 * @since 2023-04-06
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IFollowService followService;
    @Override
    public Result saveBlog(Blog blog) {
        //1,获取到用户id 把blog内容保存
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        //2 把发博客的所有好友查询出来
        List<Follow> fans = followService.query().eq("follow_user_id", user.getId()).list();
        //3 遍历所有用户 创建zset value是新添加的blog的id score是时间戳
        if (ObjectUtil.isEmpty(fans)){
            return Result.ok();
        }
        Long id = blog.getId();
        long timeTamp = System.currentTimeMillis();
        for (Follow follow:fans){
            Long userId= follow.getUserId();
            String key = RedisConstants.FEED_KEY+userId;
            redisTemplate.opsForZSet().add(key,id,timeTamp);
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogById(Long id) {
        // 1.查询blog
        Blog blog = getById(id);
        // 2.把blog对象的用户信息查询出来
        Long userId = blog.getUserId();
        // 3 把用户信息放入到blog对象里面
        User user = userService.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        //4 把商户信息查询出来
        Long shopId = blog.getShopId();
        Shop shop = shopService.getById(shopId);
        //5 把商户信息放到blog里面
        blog.setShop(shop);
        //返回
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        // 1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.判断当前登录用户是否已经点赞
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Double score = redisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            // 3.如果未点赞，可以点赞
            // 3.1.数据库点赞数 + 1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            // 3.2.保存用户到Redis的set集合  zadd key value score
            if (isSuccess) {
                redisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 4.如果已点赞，取消点赞
            // 4.1.数据库点赞数 -1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            // 4.2.把用户从Redis的set集合移除
            if (isSuccess) {
                redisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }


    private void isBlogLiked(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        // 2.判断当前登录用户是否已经点赞
        String key = "blog:liked:" + blog.getId();
        Double score = redisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }
    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        // 1.查询top5的点赞用户 zrange key 0 4
        Set<String> top5 = redisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 2.解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4.返回
        return Result.ok(userDTOS);
    }

    @Override
    public Result myFollowBlogs(Long lastId, Integer offset) {
        //获取用户信息
        Long id = UserHolder.getUser().getId();
        //到redis里面通过命令获取信息
        String key = RedisConstants.FEED_KEY+id;
        if (ObjectUtil.isEmpty(lastId)){
            lastId=System.currentTimeMillis();
        }
        //TypedTuple redis给我们提供的zset里面的一个对象 这个对象里面有两个属性一个是value一个是score
        Set<ZSetOperations.TypedTuple<Integer>> set = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key
                , 0,lastId, offset, SystemConstants.DEFAULT_PAGE_SIZE);
        //通过blogId查询到blog信息放到scrollResult的list里面
        if (ObjectUtil.isEmpty(set)){
            return Result.ok();
        }
        List<Long> bids = new ArrayList<>(set.size());
        //本页的偏移量和时间戳
        Long curTimestamp = 0L;
        Integer curOffset=1;
        //开始遍历所有的数据
        for (ZSetOperations.TypedTuple<Integer> typedTuple:set ){
            //获取到zset里面的分数
            Long timestamp =  typedTuple.getScore().longValue();
            //计算本页的偏移量
            if (timestamp.equals(curTimestamp)){
                curOffset++;
            }else {
                curOffset=1;
            }
            Long blogId=   typedTuple.getValue().longValue();
            bids.add(blogId);
            curTimestamp=timestamp;
        }
        List<Blog> list = query().in("id", bids).orderByDesc("id").list();
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(list);
        //算出最小的时间戳
        scrollResult.setMinTime(curTimestamp);
        //算出偏移量
        if (curTimestamp.equals(lastId)){
            curOffset+=offset;
        }
        scrollResult.setOffset(curOffset);
        return Result.ok(scrollResult);
    }
}